package com.easyui.shiro;

import com.easyui.pojo.User;
import com.easyui.service.MenuService;
import com.easyui.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    //每次用户点击链接的时候都调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("shiro 验证");
        List<Integer> menuIds = menuService.getUserMenuIds((Integer) principalCollection.getPrimaryPrincipal());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Integer menuId : menuIds) {
            info.addStringPermission(menuId.toString());
        }
        return info;
    }

    //登录的时候调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 因为service里已经验证过用户名密码了，所以这里不做任何验证了
        String userName = token.getUsername();
        User user = userService.getUserByName(userName);
        if (user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
    }
}
